//  MainViewController.m
//  maocuhuiOASystem
//
//  Created by michael on 16/3/20.
//  Copyright © 2016年 czd. All rights reserved.
//
#import "shouwenlistViewController.h"
#import "fawenlistViewController.h"
#import "LockController.h"
#import "xinxiViewController.h"
#import "swglViewController.h"
#import "fwglViewController.h"
#import "ksemailViewController.h"
#import "kszfViewController.h"
#import "ggxqViewController.h"
#import "SGAdvertScrollView.h"
#import "JMDropMenu.h"
#import "tongziViewController.h"
#import "daiyueViewController.h"
#import "zfyjViewController.h"
#import "wjchaxunViewController.h"
#import "gerenemailViewController.h"
#import "daibanViewController.h"
#import "MYCycleView.h"
#import "gwchaxunViewController.h"
#import "dzggViewController.h"
#import "fwclViewController.h"
#import "ViewController3.h"
#import "UIViewController+MMDrawerController.h"
#import "fwdjViewController.h"
#import "MainViewController.h"
#import "OALoginViewController.h"
#import "itemcell.h"
#import "OABaseNavViewController.h"
#import "ComingworkongController.h"
#import "emailViewController.h"
#import "iseditViewController.h"
#import "overworkingViewController.h"
#import "comingthingViewController.h"
#import "ideitworkViewController.h"
#import "workedViewController.h"
#import "OANewInViewController.h"
#import "OANewSendViewController.h"
#import "NotonewsViewController.h"
#import "webViewController.h"
#import "OAAddressViewController.h"
#import "OASMSViewController.h"
#import "MainViewCell.h"
#import "BaseModel.h"
#import "ReceieveViewController.h"
//#import "AuthHelper.h"
#define kWB_Login_NotificationName @"requestdata"

@interface HomeModel : BaseModel

@property(nonatomic,copy)NSString *  exchange;
@property(nonatomic,copy)NSString *  ksmail;
@property(nonatomic,copy)NSString *  mail;
@property(nonatomic,copy)NSString *  offiece;
@property(nonatomic,copy)NSString *  whetherExchange;
@property(nonatomic,copy)NSString *  whetherSms;
@property(nonatomic,copy)NSString * read;
@property(nonatomic,copy)NSString * trunksmail;
@property(nonatomic,copy)NSString * trunmail;
@end
@implementation HomeModel


@end
@interface MainViewController ()<UICollectionViewDelegate,UICollectionViewDataSource,SGAdvertScrollViewDelegate,JMDropMenuDelegate>
{
    int firstLoginType;

}
@property (nonatomic, strong) NSArray *titleArr;
/** imgArr */
@property (nonatomic, strong) NSArray *imageArr;
@property (nonatomic,strong) UIButton *button1;
@property (nonatomic,strong) UIButton *button2;
@property(nonatomic,strong)NSMutableArray * contentArray;
//@property (weak, nonatomic) IBOutlet UICollectionViewFlowLayout *followLayout;
//@property (weak, nonatomic) IBOutlet UICollectionView *collectionView;
//@property (nonatomic,strong) UICollectionView *collectionView;
@property (nonatomic, strong) MYCycleView *cycleView;
@property (nonatomic, strong) SGAdvertScrollView *advertScrollViewCenter;

@property(nonatomic,strong)HomeModel * homeModel;
@property(nonatomic,strong)NSMutableArray * originalData;
@property(nonatomic,strong)NSArray * array;
//@property (nonatomic, strong) AuthHelper *helper;
@end

@implementation MainViewController
static NSString * const reuseIdentifier = @"CellIdentifier";
-(NSMutableArray*)contentArray{
    if (_contentArray == nil) {
        _contentArray = [NSMutableArray array];
    }
    return _contentArray;
}

- (void)viewDidLoad {
short port = 443;                        //vpn设备端口号，一般为443
NSString *vpnIp =    @"122.224.123.170";  //vpn设备IP地址
//    self.helper = [[AuthHelper alloc] initWithHostAndPort:vpnIp port:port delegate:self];

    [super viewDidLoad];
//   if (@available(iOS 11.0, *)) {
//    self.collectionView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
//} else {
//    self.automaticallyAdjustsScrollViewInsets = NO;
//}
// 更改标题的颜色additionalSafeAreaInsets
    if (@available(iOS 11.0, *)) {
        self.additionalSafeAreaInsets= LL_ViewSafeAreInsets(self.view);
    } else {
            // Fallback on earlier versions
    }
    
    NSDictionary *attributes = [NSDictionary dictionaryWithObjectsAndKeys:

[UIColor whiteColor],NSForegroundColorAttributeName, nil];
 
[self.navigationController.navigationBar setTitleTextAttributes:attributes];
self.title = @"海宁市环保局移动办公系统";
 self.navigationController.navigationBar.barTintColor = [UIColor colorWithHexString:@"0e75de"];
 
 self.view.backgroundColor = [UIColor colorWithHexString:@"f0eff5"];
 
 
   [self _backbutton];
     self.cycleView = [[MYCycleView alloc] initWithFrame:CGRectMake(0,kTopHeight, [UIScreen mainScreen].bounds.size.width, (KScreenHeight-kTopHeight)*1/3)];

//    当imageArray.cout为1时，不轮播，相当于imageView;
    self.cycleView.imageArray = @[@"pic_01.jpg",@"pic_02.jpg",@"pic_03.jpg",@"pic_04.jpg"];
//    设置轮播时间，小于0时逆向，大于0时正向，等于0是不自动轮播
    self.cycleView.second = 2;
////    设置pageControl未选中indicator的颜色
    self.cycleView.pageIndicatorColor = [UIColor whiteColor];
////    设置pageControl当前indicator的颜色
    self.cycleView.currentIndicatorColor = [UIColor yellowColor];
    
    self.cycleView.bannerClick = ^(NSInteger index) {
        
        NSLog(@"点击了%zd",index);
        
    };
//        [self.view addSubview:self.cycleView];

//    UIView *bgview = [[UIView alloc]initWithFrame:CGRectMake(0, _cycleView.bottom, KScreenWidth, 40)];
//    bgview.backgroundColor = [UIColor whiteColor];
//     _newslabel = [[UILabel alloc]initWithFrame:CGRectMake(40, 5,KScreenWidth-50, 30)];
//_newslabel.numberOfLines = 0;
//_newslabel.textColor = [UIColor blackColor];
//
//     NSString *string =[NSString stringWithFormat:@"系统公告:xxxxxxx"];
//
//     NSMutableAttributedString *attrStr = [[NSMutableAttributedString alloc] initWithString:string];
//      [attrStr addAttribute:NSForegroundColorAttributeName
//                value:[UIColor colorWithHexString:@"0e75de"]
//                range:NSMakeRange(0, 5)];
//_newslabel.attributedText = attrStr;
//
//    _newslabel.font = [UIFont systemFontOfSize:14];
//    [bgview addSubview:_newslabel];
//    [self.view addSubview:bgview];
  

 UICollectionViewFlowLayout *followLayout = [[UICollectionViewFlowLayout alloc]init];
     followLayout.itemSize = CGSizeMake((KScreenWidth-3)/ 4,(KScreenWidth-3)/ 4 );

self.collectionView  = [[UICollectionView alloc]initWithFrame:CGRectMake(0,0, KScreenWidth, self.view.height-kTopHeight-49-_cycleView.height) collectionViewLayout:followLayout];
[self.view addSubview :_collectionView];
_collectionView.backgroundColor = [UIColor clearColor];
_collectionView.scrollEnabled = NO;
_collectionView.delegate = self;
_collectionView.dataSource = self;
    [_collectionView registerNib:[UINib nibWithNibName:@"MainViewCell" bundle:nil] forCellWithReuseIdentifier:@"FansCellId"];
     followLayout.minimumLineSpacing =1;
        followLayout.minimumInteritemSpacing =1;
// 判断版本
//定时器
//[self setupSubView];
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];

     dispatch_async(dispatch_get_global_queue(0, 0), ^{
        _timer = [NSTimer scheduledTimerWithTimeInterval:300 target:self selector:@selector(news) userInfo:nil repeats:YES];
        // 开启当前线程
        [[NSRunLoop currentRunLoop] run];
    });

      //修改返回按钮的颜色和字体
  self.navigationController.navigationBar.tintColor = [UIColor whiteColor];
   UIBarButtonItem *barButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"返回" style:UIBarButtonItemStyleDone target:nil action:nil];
    self.navigationItem.backBarButtonItem = barButtonItem;
//UIView *view1 = [[UIView alloc]initWithFrame:CGRectMake(0, self.view.bottom-50, 50, 30)];
//    view1.backgroundColor = [UIColor yellowColor];
//    [self.view addSubview:view1];
}

- (void)upApp{
 //获取app版本号
  NSString * userId = [[NSUserDefaults standardUserDefaults]objectForKey:@"userId"];
    NSDictionary *infoDictionary = [[NSBundle mainBundle] infoDictionary];
    NSString *appVersion = [infoDictionary objectForKey:@"CFBundleShortVersionString"];
    
    
    NSArray *array = @[@{@"veseion":appVersion},@{@"userId":userId}];

[HttpTools requestWithURL:KExchmain arrays:array method:@"updateDown" success:^(id JSON) {
if (![JSON isKindOfClass:[NSDictionary class]]) {
    [self.view makeToast:@"服务器出错!"];
}
//if ([JSON isEqualToString:@"-1044"]) {
//    [self.view makeToast:@"服务器出错!"];
//}
else{
         NSArray *tempArray  = JSON[@"data"];
        NSDictionary * dict = [tempArray firstObject];
            NSString *url = dict[@"downlink"];
        NSString *index = dict[@"result"];
    
    
    if ([index isEqualToString:@"1"]) {
            
// 提示更新
            UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"更新" message:@"海宁环保APP已经更新，请点击更新进行更新" preferredStyle:UIAlertControllerStyleAlert];

            UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel  handler:^(UIAlertAction * _Nonnull action) {
                
//    [[AuthHelper getInstance] logoutVpn];
      UIStoryboard * storyBoard = [UIStoryboard storyboardWithName:@"Main" bundle:nil];

    OALoginViewController * loginVC =  [storyBoard instantiateViewControllerWithIdentifier:@"LoginVC"];
             loginVC.type = @"1";

    self.view.window.rootViewController = loginVC;
                
            }];

            UIAlertAction *action = [UIAlertAction actionWithTitle:@"更新" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                
                if (url.length != 0) {
                    
                    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:url]];

                }
                
            }];
            
            [alert addAction:cancelAction];
            [alert addAction:action];
            
            [self presentViewController:alert animated:YES completion:nil];
            
            
       }
            
        }

    }failure:^(NSError *error) {
        
    }];

    

}

- (void)dealloc
{
    // 移除通知
    [[NSNotificationCenter defaultCenter] removeObserver:self name:kWB_Login_NotificationName object:nil];
    }
// 使用storyboard创建的控制调用的初始化方法
- (instancetype)initWithCoder:(NSCoder *)coder
{
    self = [super initWithCoder:coder];
    if (self) {
        // 注册通知
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(news) name:kWB_Login_NotificationName object:nil];
       
        
    }
    return self;
}

-(void)viewWillAppear:(BOOL)animated{
short port = 443;                        //vpn设备端口号，一般为443
NSString *vpnIp =    @"112.11.119.146";  //vpn设备IP地址
 if ([[[NSUserDefaults standardUserDefaults] objectForKey:@"shoushi"] isEqualToString:@"Y"]) {
  [self upApp];

    [self news];
// self.helper = [AuthHelper getInstance];
//    SdkMode mode = EasyApp;
////    if (enableL3VPN.isOn) {
////        mode = L3VPN;
////    }
//            firstLoginType = SSL_AUTH_TYPE_PASSWORD;
//
//        [self.helper init:mode host:vpnid port:port delegate:self];
    }else{
    [self upApp];

    [self news];

    }
//[self upApp];
//[self makeview];
}
//#pragma mark -
//#pragma mark SangforSDKDelegate
//- (void) onCallBack:(const VPN_RESULT_NO)vpnErrno authType:(const int)authType
//{
//    switch (vpnErrno)
//    {
//        case RESULT_VPN_INIT_FAIL:
//
////            statusView.text = @"Vpn Init failed!！！！";
////            say_err("Vpn Init failed");
//            break;
//
//        case RESULT_VPN_AUTH_FAIL:
//        {
//            [MBProgressHUD hideHUDForView:self.view animated:YES];
//            [self.helper clearAuthParam:@SET_RND_CODE_STR];
//            [self.helper vpnQueryStatus];
////            NSString *strUFT8 = [[NSString alloc] initWithUTF8String:ssl_vpn_get_err()];
////            statusView.text = [[NSString alloc] initWithFormat:@"%@,%@", @"vpn auth failed ",strUFT8];
////            say_err("vpn auth failed");
//
////            NSRange range = [strUFT8 rangeOfString:@"psw_errorCode"];
////            if(range.location != NSNotFound){
////                NSString* info = ssl_get_password_safe_policy_prompt(get_err());//获取密码策略失败原因
////                statusView.text = info;
////            }
//            break;
//        }
//        case RESULT_VPN_INIT_SUCCESS:
//        {
////            statusView.text = @"vpn init success";
//            //显示当前sdk版本号
//            NSString *version = [self.helper getSdkVersion];
//            NSLog(@"sdk version is %@",version);
//            [self.helper setAuthParam:@AUTH_DEVICE_LANGUAGE param:@"en_US"];//zh_CN or en_US
//
//            switch (firstLoginType) {
//                case SSL_AUTH_TYPE_PASSWORD:
//                {
//                    if (![self initPswAuthParam]) {
////                        statusView.text = @"vpn init password param failed!!";
//                        return;
//                    }
//                    break;
//                }
////                case SSL_AUTH_TYPE_CERTIFICATE:
////                {
////                    if (![self initCertAuthParam]) {
////                        statusView.text = @"vpn init cert param failed!!";
////                        return;
////                    }
////                    break;
////                }
////                case SSL_AUTH_TYPE_TWFID:
////                {
////                    //session共享登录-子app only:从keychain中提取session ，并登录
////                    KeychainItemWrapper *wrapper= [[KeychainItemWrapper alloc] initWithIdentifier:@"Account Number" accessGroup:@"com.sangfor.SdkDemo"];
////                    NSData *session = [wrapper objectForKey:(id)kSecValueData];
////                    //设置认证参数
////                    ssl_set_sessionid(session.bytes, (int)session.length);
////                    break;
////                }
////                default:
////                    break;
//            }
//
//            [MBProgressHUD showHUDAddedTo:self.view animated:YES];
//
//            [self.helper loginVpn:firstLoginType];
//
//            break;
//        }
//
//        case RESULT_VPN_AUTH_SUCCESS:
////            statusView.text = [NSString stringWithFormat:@"start other auth:%d.", authType];
//            [self startOtherAuth:authType];
//            break;
//        case RESULT_VPN_AUTH_LOGOUT:
//            NSLog(@"Vpn logout success!");
//            break;
//        case RESULT_VPN_OTHER:
//            if (VPN_OTHER_RELOGIN_FAIL == (VPN_RESULT_OTHER_NO)authType) {
//                NSLog(@"Vpn relogin failed, maybe network error");
//            }
//            break;
//
//        case RESULT_VPN_NONE:
//            break;
//
//        case RESULT_VPN_L3VPN_FAIL: {
//            [MBProgressHUD hideHUDForView:self.view animated:YES];
//            [self.helper clearAuthParam:@SET_RND_CODE_STR];
////            NSString *strUFT8 = [[NSString alloc] initWithUTF8String:get_err()];
////            statusView.text = [[NSString alloc] initWithFormat:@"%@,%@", @"l3vpn start fail ",strUFT8];
////            say_err("l3vpn start failed");
//            break;
//        }
//
//        default:
//            break;
//    }
//}
//-(BOOL)initCertAuthParam
//{
//
//
//    [self.helper setAuthParam:@CERT_AUTH_SLECT_AUTH param:@"1"];
//    [self.helper setAuthParam:@ACCESS_GROUPS_SHARE_KEY param:@"com.test"];
//    return YES;
//}
//- (void) startOtherAuth:(const int)authType
//{
//    switch (authType)
//    {
//        case SSL_AUTH_TYPE_CERTIFICATE:
//        {
//            say_log("Start certificate Auth!!!");
//            [self initCertAuthParam];
//            break;
//        }
//        case SSL_AUTH_TYPE_PASSWORD:
//        {
//            say_log("Start Password Name Auth!!!");
//            [self initPswAuthParam];
//             break;
//        }
//        case SSL_AUTH_TYPE_NONE:
//        {
//            //session共享登录--主程序only：登录成功之后读取session，然后将它保存到keychain
//
//            /*
//             char buffer[64];
//             int sessionLen = ssl_get_sessionid(buffer, 64);
//             NSData *data = [NSData dataWithBytes:buffer length:sessionLen];
//             KeychainItemWrapper *wrapper = [[KeychainItemWrapper alloc] initWithIdentifier:@"Account Number" accessGroup:@"com.sangfor.SdkDemo"];
//             [wrapper setObject:data forKey:(id)kSecValueData];
//             */
//
//
//            [MBProgressHUD hideHUDForView:self.view animated:YES];
//            say_log("Vpn Auth success!");
////            statusView.text = @"vpn Auth success";
//[self upApp];
//[self news];
//
////            [self performSelectorOnMainThread:@selector(loginSuccessAction) withObject:nil waitUntilDone:NO];
////            [self saveUserConf];
//
//            return;
//        }
//        case SSL_AUTH_TYPE_SMS:
//        {
//            NSString *phoneNumber = [self.helper getSmsPhoneNumber];//发送手机号
//            NSString *countdown = [self.helper getSmsCountDown];//发送间隔时间（vpn服务器上配置的）,可用于做定时器，比如多少时间后可以重新获取短信。
//            NSLog(@"phone number is %@",phoneNumber);
//            NSLog(@"coundown  is %@",countdown);
////            statusView.text = [[NSString alloc] initWithFormat:@"phone number is %@, coundown  is %@", phoneNumber, countdown];
//        }
//        case SSL_AUTH_TYPE_RADIUS:
//        {
//            [MBProgressHUD hideHUDForView:self.view animated:YES];
//            return;
//        }
//        case SSL_AUTH_TYPE_TOKEN: {
////            NSString *token = codeTF.text;
////            [self.helper setAuthParam:@"Token.Auth.Code" param:token];
//        } break;
//        default:
//            say_log("Other failed!!!");
//            return;
//    }
//    [self.helper loginVpn:authType];
//}
//-(BOOL)initPswAuthParam
//{
////NSString *userName = @"testfz";             //用户名认证的用户名
////NSString *password = @"123456";
//           //用户名认证的密码
//                      NSString *userName = [[NSUserDefaults standardUserDefaults] objectForKey:@"shouquanid"];
//
//    NSString *username = userName;
//    NSString *passWord = userName;
//
//    if (!username || username.length == 0) {
//        return NO;
//    }
//
//    [self.helper setAuthParam:@PORPERTY_NamePasswordAuth_NAME param:username];
//    [self.helper setAuthParam:@PORPERTY_NamePasswordAuth_PASSWORD param:passWord];
//
//    return YES;
//}
- (void)news{
//    [MBProgressHUD showHUDAddedTo:self.view animated:YES];

 NSString * userId = [[NSUserDefaults standardUserDefaults]objectForKey:@"userId"];
    NSArray *  array = @[@{@"userId":userId}];;
    [HttpTools requestWithURL:KExchmain arrays:array method:KHomePqwoiunu success:^(id JSON) {
          [MBProgressHUD hideAllHUDsForView:self.view animated:YES];

    if (![JSON isKindOfClass:[NSDictionary class]]) {
    [self.view makeToast:@"服务器出错!"];
}else{
    NSLog(@"%@",JSON);
//    info
    _newsList = JSON[@"unit"];
    _zhiweiList = JSON[@"info"];
//        [self initbutton];

         NSArray *tempArray  = JSON[@"data"];
        NSDictionary * dict = [tempArray firstObject];
 
        self.homeModel = [[HomeModel alloc] initWitDictionary:dict];
                    [self setupSubView];

            [self.collectionView reloadData];
            }

    } failure:^(NSError *error) {
              [MBProgressHUD hideAllHUDsForView:self.view animated:YES];
    [self.view makeToast:@"网络连接超时,请检查网络"];

    }];
  


}
- (void)initbutton{
[_bgview removeFromSuperview];
NSMutableArray *newarray = [NSMutableArray array];
for (NSDictionary *dic in _newsList) {
    [newarray addObject:dic[@"subject"]];
}
NSMutableArray *zhiweiarray = [NSMutableArray array];
for (NSDictionary *dic in _zhiweiList) {
    [zhiweiarray addObject:dic[@"unit"]];
}
    _titleArr =zhiweiarray;
if (!_bgview) {
    
}
 _bgview = [[UIView alloc]initWithFrame:CGRectMake(0, _cycleView.bottom, KScreenWidth, 40)];
    _bgview.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:_bgview];
UIImageView *image = [[UIImageView alloc]initWithFrame:CGRectMake(10, 10, 20, 20)];
image.image = [UIImage imageNamed:@"horn_icon"];
    [_bgview addSubview:image];

_advertScrollViewCenter = [[SGAdvertScrollView alloc]initWithFrame:CGRectMake(image.right+10,0, KScreenWidth-image.width-10, 40)];
_advertScrollViewCenter.scrollTimeInterval = 10;
    _advertScrollViewCenter.titleColor = [[UIColor blackColor] colorWithAlphaComponent:0.7];
    _advertScrollViewCenter.scrollTimeInterval = 5;
    _advertScrollViewCenter.titleFont = [UIFont systemFontOfSize:14];
    _advertScrollViewCenter.delegate = self;
        _advertScrollViewCenter.titles = newarray ;

        [_bgview addSubview:_advertScrollViewCenter];
        if (_zhiweiList.count ==1) {
    self.title = _zhiweiList[0][@"unit"];
}else{
if (!_titlebutton) {
     _titlebutton = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 200, 44)];
  [_titlebutton setTitle:_zhiweiList[0][@"unit"] forState:UIControlStateNormal];
    [_titlebutton setTitleColor:[UIColor whiteColor]forState:UIControlStateNormal];
    [_titlebutton setImage:[UIImage imageNamed:@"白下拉"] forState:UIControlStateNormal];
    _titlebutton.titleLabel.font = [UIFont systemFontOfSize: 16.0];
        [_titlebutton layoutButtonWithEdgeInsetsStyle:MKButtonEdgeInsetsStyleRight
                                    imageTitleSpace:10];
   [_titlebutton addTarget:self action:@selector(xialaaction) forControlEvents:UIControlEventTouchUpInside];
        self.navigationItem.titleView = _titlebutton;
}
 
}

}
- (void)advertScrollView:(SGAdvertScrollView *)advertScrollView didSelectedItemAtIndex:(NSInteger)index {
NSMutableArray *newarray = [NSMutableArray array];
for (NSDictionary *dic in _newsList) {
    [newarray addObject:dic[@"subject"]];
}
 NSString *idstring = [NSString string];
 for (NSDictionary *dic in _newsList) {
 if ([dic[@"subject" ]isEqualToString:newarray[index]]) {
 idstring = dic[@"unid"];
}
}
      UIStoryboard * storyBoard = [UIStoryboard storyboardWithName:@"Main" bundle:nil];

//     detailViewController * vc = (detailViewController *)[storyBoard instantiateViewControllerWithIdentifier:@"detail"];
tongziViewController *vc = [[tongziViewController alloc]init];
vc.type = @"gonggao";
vc.fileId = idstring;
[self.navigationController pushViewController:vc animated:YES];
}
- (void)xialaaction{
//    self.titleArr = @[@"创建群聊",@"加好友/群"];

    self.imageArr = @[@"img1",@"img2",@"img3",@"img4",@"img5"];

[JMDropMenu showDropMenuFrame:CGRectMake(KScreenWidth/2-90, kTopHeight, 180, 40*_titleArr.count) ArrowOffset:90 TitleArr:self.titleArr ImageArr:_imageArr Type:JMDropMenuTypeQQ LayoutType:JMDropMenuLayoutTypeTitle RowHeight:40.f Delegate:self];
}



- (void)didSelectRowAtIndex:(NSInteger)index Title:(NSString *)title Image:(NSString *)image {
NSString *idstring = [NSString string];
for (NSDictionary *dic in _zhiweiList) {
    if ([title isEqualToString:dic[@"unit"]]) {
    idstring = dic[@"path"];
}
}
// [MBProgressHUD showHUDAddedTo:self.view animated:YES];

 NSString * userId = [[NSUserDefaults standardUserDefaults]objectForKey:@"userId"];
    NSArray *  array = @[@{@"userId":userId},@{@"path":idstring}];;
    [HttpTools requestWithURL:KExchmain arrays:array method:@"changeunit" success:^(id JSON) {
          [MBProgressHUD hideAllHUDsForView:self.view animated:YES];

    if ([[NSString stringWithFormat:@"%@",JSON]isEqualToString:@"25"]) {
    [_titlebutton setTitle:title forState:UIControlStateNormal];
      [_titlebutton layoutButtonWithEdgeInsetsStyle:MKButtonEdgeInsetsStyleRight
                                    imageTitleSpace:10];
    
    [self news];
}else{
    [self.view makeToast:@"服务器出错!"];
}

  

    } failure:^(NSError *error) {
              [MBProgressHUD hideAllHUDsForView:self.view animated:YES];

    }];
    NSLog(@"index----%zd,  title---%@, image---%@", index, title, image);
}
-(void)setupSubView{
//    if ([[_dic objectForKey:@"whetherExchange"] isEqualToString:@"1"])
        if([self.homeModel.whetherExchange isEqualToString:@"1"])
 {
         NSString * filePath =  [[NSBundle mainBundle] pathForResource:@"mainList" ofType:@"plist"];
    self.originalData = [NSMutableArray arrayWithContentsOfFile:filePath];
    [self.contentArray addObjectsFromArray:self.originalData];    }else  {
    //不显示
          NSString * filePath =  [[NSBundle mainBundle] pathForResource:@"mainList" ofType:@"plist"];
    self.originalData = [NSMutableArray arrayWithContentsOfFile:filePath];
    [self.contentArray addObjectsFromArray:self.originalData];
    
    }

    
    self.contentArray = [self.originalData mutableCopy];
    [self.collectionView reloadData];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}



- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return self.contentArray.count;
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
MainViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"FansCellId" forIndexPath:indexPath];
    NSDictionary * dict = self.contentArray[indexPath.item];
    cell.dict = dict;

if ([dict[@"title"] isEqualToString:@"待办文件"]) {


NSInteger i = [self.homeModel.offiece integerValue];
if (i>99) {
            [cell.btnCount setTitle:@"99+" forState:UIControlStateNormal];
}else{
        [cell.btnCount setTitle:self.homeModel.offiece forState:UIControlStateNormal];
        }
        if ([self.homeModel.offiece integerValue] !=0) {
            cell.btnCount.hidden = NO;
        }else{
            cell.btnCount.hidden = YES;
        }
    }
    else if ([dict[@"title"]isEqualToString:@"收文管理"]) {
    NSInteger i = [self.homeModel.exchange integerValue];
if (i>99) {
            [cell.btnCount setTitle:@"99+" forState:UIControlStateNormal];
}else{
        [cell.btnCount setTitle:self.homeModel.exchange forState:UIControlStateNormal];
        }
        if( [self.homeModel.exchange integerValue]!=0 ) {
            cell.btnCount.hidden = NO;
        }else{
            cell.btnCount.hidden = YES;
        }
        
    } else if ([dict[@"title"]isEqualToString:@"单位邮件"]) {
    NSInteger i = [self.homeModel.ksmail integerValue];
if (i>99) {
            [cell.btnCount setTitle:@"99+" forState:UIControlStateNormal];
}else{
        [cell.btnCount setTitle:self.homeModel.ksmail forState:UIControlStateNormal];
        }
        if( [self.homeModel.ksmail integerValue]!=0 ) {
            cell.btnCount.hidden = NO;
        }else{
            cell.btnCount.hidden = YES;
        }
        
    }else if ([dict[@"title"]isEqualToString:@"单位转办"]) {
    NSInteger i = [self.homeModel.trunksmail integerValue];
if (i>99) {
            [cell.btnCount setTitle:@"99+" forState:UIControlStateNormal];
}else{
        [cell.btnCount setTitle:self.homeModel.trunksmail forState:UIControlStateNormal];
        }
        if( [self.homeModel.trunksmail integerValue]!=0 ) {
            cell.btnCount.hidden = NO;
        }else{
            cell.btnCount.hidden = YES;
        }
        
    }else if ([dict[@"title"]isEqualToString:@"转办文件"]) {
    NSInteger i = [self.homeModel.trunmail integerValue];
if (i>99) {
            [cell.btnCount setTitle:@"99+" forState:UIControlStateNormal];
}else{
        [cell.btnCount setTitle:self.homeModel.trunmail forState:UIControlStateNormal];
        }
        if( [self.homeModel.trunmail integerValue]!=0 ) {
            cell.btnCount.hidden = NO;
        }else{
            cell.btnCount.hidden = YES;
        }
        
    }
    else if ([dict[@"title"]isEqualToString:@"待阅文件"]) {
    NSInteger i = [self.homeModel.read integerValue];
if (i>99) {
            [cell.btnCount setTitle:@"99+" forState:UIControlStateNormal];
}else{
        [cell.btnCount setTitle:self.homeModel.read forState:UIControlStateNormal];
        }
//        [cell.btnCount setTitle:self.homeModel.read forState:UIControlStateNormal];
        if ([self.homeModel.read integerValue] !=0) {
            cell.btnCount.hidden = NO;
        }else{
            cell.btnCount.hidden = YES;
        }
        
    }
    
    else if ([dict[@"title"] isEqualToString:@"电子邮件"]) {
      NSInteger i = [self.homeModel.mail integerValue];
if (i>99) {
            [cell.btnCount setTitle:@"99+" forState:UIControlStateNormal];
}else{
        [cell.btnCount setTitle:self.homeModel.mail forState:UIControlStateNormal];
        }
//        [cell.btnCount setTitle:self.homeModel.mail forState:UIControlStateNormal];
        if ([self.homeModel.mail integerValue] !=0) {
            cell.btnCount.hidden = NO;
        }else{
            cell.btnCount.hidden = YES;
        }
    }else{
        cell.btnCount.hidden = YES;
    }
    [cell layoutIfNeeded];
    return cell;

}
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
// NSLog(@"cell #%ld was selected", (long)indexPath.row);
 NSDictionary * dict =  self.contentArray[indexPath.item];
     UIStoryboard * storyBoard = [UIStoryboard storyboardWithName:@"Main" bundle:nil];

       if ([dict[@"title"] isEqualToString:@"待办文件"]) {
daibanViewController *vc = [[daibanViewController alloc]init];
  vc.hidesBottomBarWhenPushed = YES;

[self.navigationController pushViewController:vc animated:YES];

} if ([dict[@"title"] isEqualToString:@"电子邮件"]) {
gerenemailViewController *vc = [[gerenemailViewController alloc]init];
  vc.hidesBottomBarWhenPushed = YES;

[self.navigationController pushViewController:vc animated:YES];

}
 if ([dict[@"title"] isEqualToString:@"转办文件"]) {
zfyjViewController *vc = [[zfyjViewController alloc]init];
  vc.hidesBottomBarWhenPushed = YES;

[self.navigationController pushViewController:vc animated:YES];

}
 if ([dict[@"title"] isEqualToString:@"最新发文"]) {
fawenlistViewController *vc = [[fawenlistViewController alloc]init];
[self.navigationController pushViewController:vc animated:YES];
    
} if ([dict[@"title"] isEqualToString:@"最新收文"]){
shouwenlistViewController *vc = [[shouwenlistViewController alloc]init];
[self.navigationController pushViewController:vc animated:YES];

}
if ([dict[@"title"] isEqualToString:@"文件查询"]) {
     gwchaxunViewController *comvc = [[gwchaxunViewController alloc]init];
    comvc.hidesBottomBarWhenPushed = YES;

    [self.navigationController pushViewController:comvc animated:YES];
    }
    
     if ([dict[@"title"] isEqualToString:@"局内通告"]) {
     dzggViewController *comvc = [[dzggViewController alloc]init];
comvc.hidesBottomBarWhenPushed = YES;

    [self.navigationController pushViewController:comvc animated:YES];
    }
    
      if ([dict[@"title"] isEqualToString:@"待阅文件"]) {
     daiyueViewController *comvc = [[daiyueViewController alloc]init];
comvc.hidesBottomBarWhenPushed = YES;

    [self.navigationController pushViewController:comvc animated:YES];
    }
    
    
    if ([dict[@"title"] isEqualToString:@"人员查询"]) {
   OAAddressViewController * addressVC = (OAAddressViewController*)[storyBoard instantiateViewControllerWithIdentifier:@"AddressVCID"];
        [self.navigationController pushViewController:addressVC animated:YES];
    }
  if ([dict[@"title"] isEqualToString:@"收文管理"]) {
     swglViewController *comvc = [[swglViewController alloc]init];
        [self.navigationController pushViewController:comvc animated:YES];
    }
    if ([dict[@"title"] isEqualToString:@"发文管理"]) {
     fwglViewController *comvc = [[fwglViewController alloc]init];
        [self.navigationController pushViewController:comvc animated:YES];
    }
    if ([dict[@"title"] isEqualToString:@"单位邮件"]) {
     ksemailViewController *comvc = [[ksemailViewController alloc]init];
        [self.navigationController pushViewController:comvc animated:YES];
    }
     if ([dict[@"title"] isEqualToString:@"单位转办"]) {
     kszfViewController *comvc = [[kszfViewController alloc]init];
        [self.navigationController pushViewController:comvc animated:YES];
    } if ([dict[@"title"] isEqualToString:@"信息简报"]) {
    xinxiViewController  *comvc = [[xinxiViewController alloc]init];
        [self.navigationController pushViewController:comvc animated:YES];
    }
    
     if ([dict[@"title"] isEqualToString:@"收文处理"]) {
   ComingworkongController *comvc =(ComingworkongController *) [self.storyboard instantiateViewControllerWithIdentifier:@"comvc"];
                                             comvc.hidesBottomBarWhenPushed = YES;

    [self.navigationController pushViewController:comvc animated:YES];
    }
     if ([dict[@"title"] isEqualToString:@"发文处理"]) {
     fwclViewController *comvc = [[fwclViewController alloc]init];
                                             comvc.hidesBottomBarWhenPushed = YES;

    [self.navigationController pushViewController:comvc animated:YES];
    }
    
   



    if ([dict[@"title"] isEqualToString:@"已办公文"]) {
  iseditViewController *isedvc =(iseditViewController *) [self.storyboard instantiateViewControllerWithIdentifier:@"isedit"];
    [self.navigationController pushViewController:isedvc animated:YES];
    }
    if ([dict[@"title"] isEqualToString:@"办结公文"]) {
   overworkingViewController *overvc = (overworkingViewController *)[self.storyboard instantiateViewControllerWithIdentifier:@"over"];
    [self.navigationController pushViewController:overvc animated:YES];
    }
    if ([dict[@"title"] isEqualToString:@"待办事项"]) {
   comingthingViewController *comthvc = (comingthingViewController *)[self.storyboard instantiateViewControllerWithIdentifier:@"comingthing"];
       [self.navigationController pushViewController:comthvc animated:YES];
    }
    if ([dict[@"title"] isEqualToString:@"已办事项"]) {
   ideitworkViewController *ideitvc = (ideitworkViewController *)[self.storyboard instantiateViewControllerWithIdentifier:@"ideit"];
    [self.navigationController pushViewController:ideitvc animated:YES];
    }
    if ([dict[@"title"] isEqualToString:@"办结事项"]) {
workedViewController *worked = (workedViewController *)[self.storyboard instantiateViewControllerWithIdentifier:@"worked"];
    [self.navigationController pushViewController:worked animated:YES];
    }
    if ([dict[@"title"] isEqualToString:@"通知通告"]) {
     NotonewsViewController *notonews = (NotonewsViewController *)[self.storyboard instantiateViewControllerWithIdentifier:@"notonews"];
    [self.navigationController pushViewController:notonews animated:YES];    }
  
//    if ([dict[@"title"] isEqualToString:@"最新收文"]) {
//OANewInViewController *oAnewView =  (OANewInViewController *)[self.storyboard instantiateViewControllerWithIdentifier:@"OANewInView"];
//   //OANewInView
//    [self.navigationController pushViewController:oAnewView animated:YES];
//    }
//    if ([dict[@"title"] isEqualToString:@"最新发文"]) {
//   OANewSendViewController *oAnewSend = (OANewSendViewController *)[self.storyboard instantiateViewControllerWithIdentifier:@"OANewIn"];
//    [self.navigationController pushViewController:oAnewSend animated:YES];
//    }
    if ([dict[@"title"] isEqualToString:@"通讯录"]) {
   OAAddressViewController * addressVC = (OAAddressViewController*)[self.storyboard instantiateViewControllerWithIdentifier:@"AddressVCID"];
        [self.navigationController pushViewController:addressVC animated:YES];
    }
    if ([dict[@"title"] isEqualToString:@"短信平台"]) {
   OASMSViewController *smvc = (OASMSViewController *)[ self.storyboard instantiateViewControllerWithIdentifier:@"SMSVCID"];
                                                smvc.hidesBottomBarWhenPushed = YES;

    [self.navigationController pushViewController:smvc animated:YES];
    }

   }


- (void)_backbutton{
UIBarButtonItem *item1 = [[UIBarButtonItem alloc] initWithTitle:@"退出"style:UIBarButtonItemStylePlain target:self action:@selector(rightButtonAction:)];

                     self.navigationItem.rightBarButtonItem = item1;
 


     UIBarButtonItem * rightItem1  = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"3、首页-更多"] style:UIBarButtonItemStylePlain target:self action:@selector(createNewSMSAction)];
   UIButton *liftButton = [UIButton buttonWithType:UIButtonTypeCustom];
liftButton.frame = CGRectMake(0, 0,95*.6, 72*.6);
[liftButton setImage:[UIImage imageNamed:@"3、首页-logo"] forState:UIControlStateDisabled];
UIBarButtonItem *rightItem2 = [[UIBarButtonItem alloc] initWithCustomView:liftButton];
 liftButton.enabled = NO;
//[self.navigationItem setLeftBarButtonItems:@[rightItem1,rightItem2]];
[self.navigationItem setLeftBarButtonItems:@[rightItem1]];

    
}
-(void)createNewSMSAction{
    
     [self.mm_drawerController toggleDrawerSide:MMDrawerSideLeft animated:YES completion:nil];   

    
}
- (void)makeview{

 NSString * userId = [[NSUserDefaults standardUserDefaults]objectForKey:@"userId"];
    NSArray *  array = @[@{@"userId":userId}];;
    [HttpTools requestWithURL:KExchmain arrays:array method:KHomePqwoiunu success:^(id JSON) {
        NSArray *tempArray  = JSON[@"data"];
        NSDictionary * dict = [tempArray firstObject];
        self.homeModel = [[HomeModel alloc] initWitDictionary:dict];
        [self setupSubView];
    } failure:^(NSError *error) {
        
    }];
}

- (void)rightButtonAction:(UIButton *)button {

 UIAlertView * alertView = [[UIAlertView alloc] initWithTitle:nil message:@"是否退出系统" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
    [alertView show];
}
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
//    if (buttonIndex == 1)
//    {
//    [[NSUserDefaults standardUserDefaults]removeObjectForKey:@"auto"];
//    if (![[NSUserDefaults standardUserDefaults] objectForKey:@"remember"])
//    {
//    [[NSUserDefaults standardUserDefaults] removeObjectForKey:@"remember"];
//    [[NSUserDefaults standardUserDefaults]removeObjectForKey:@"userId"];
//    [[NSUserDefaults standardUserDefaults]removeObjectForKey:@"pwdId"];
//    }
//          // [[NSUserDefaults standardUserDefaults] setObject:@(NO) forKey:@"remember"];
//
//       OALoginViewController * loginVC = (OALoginViewController*) [self.storyboard instantiateViewControllerWithIdentifier:@"LoginVC"];
//        UINavigationController * nav = [[UINavigationController alloc]initWithRootViewController:loginVC];
//        self.view.window.rootViewController = nav;
//        nav.navigationBar.hidden = YES;
//    }
if (buttonIndex == 1){
// [_helper logoutVpn];


if ([[[NSUserDefaults standardUserDefaults]objectForKey:@"shoushi"] isEqualToString:@"Y"]) {
  LockController *lockController = [[LockController alloc]init];
         self.view.window.rootViewController = lockController;
}else{
//    [[AuthHelper getInstance] logoutVpn];


       UIStoryboard * storyBoard = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
//[[NSUserDefaults standardUserDefaults] setObject:@"N" forKey:@"shoushi"];

 OALoginViewController * loginVC =  [storyBoard instantiateViewControllerWithIdentifier:@"LoginVC"];
     [[NSUserDefaults standardUserDefaults] setObject:@"N" forKey:@"autoLogin"];
     loginVC.type = @"1";
    self.view.window.rootViewController = loginVC;


}
}
}
@end
